import code
import json
import os
from tokenize import String
from webbrowser import Elinks
import subprocess
import random
import string
from generate_words_util import GenerateWordsUtil

class GenerateUIKitCodes:

    def __init__(self):
        
        self.gen_words = GenerateWordsUtil()

        self.actions = []

    
    def set_uikit_properties(self, var_name, properties, var_type=None, is_return=False, var_des:String=None):
        """设置UI控件的属性"""
        code_lines = []
        for prop, value in properties.items():
            if prop == "backgroundColor":
                code_lines.append(f"{var_name}.backgroundColor = {self.swift_color_from_value(value)}")
            elif prop == "cornerRadius":
                code_lines.append(f"{var_name}.layer.cornerRadius = {value}\n{var_name}.layer.masksToBounds = true")
            elif prop == "contentMode":
                code_lines.append(f"{var_name}.contentMode = .{value}\n{var_name}.clipsToBounds = true")
            elif prop == "isHidden":
                code_lines.append(f"{var_name}.isHidden = {str(value).lower()}")
            elif prop == "isUserInteractionEnabled":
                code_lines.append(f"{var_name}.isUserInteractionEnabled = {str(value).lower()}")
            elif prop == "alpha":
                code_lines.append(f"{var_name}.alpha = {value}")
            
            # UILabel的属性
            elif prop == "text":
                code_lines.append(f"{var_name}.text = \"{value}\".localized()")
            elif prop == "numberOfLines":
                code_lines.append(f"{var_name}.numberOfLines = {value}")
            elif prop == "textColor":
                code_lines.append(f"{var_name}.textColor = {self.swift_color_from_value(value)}")
            elif prop == "fontSize":

                if var_type == "UILabel":
                    code_lines.append(f"{var_name}.font = .systemFont(ofSize: {value}, weight: .{properties.get('fontWeight', 'regular')})")
                elif var_type == "UIButton":
                    code_lines.append(f"{var_name}.titleLabel?.font =.systemFont(ofSize: {value}, weight:.{properties.get('fontWeight', 'regular')})")
            
            # UIImageView的属性
            elif prop == "image":
                if var_type == "UIImageView":
                    code_lines.append(f"{var_name}.image =.caTimagePath(\"{value}\")")
                elif var_type == "UIButton":
                    code_lines.append(f"{var_name}.setImage(.caTimagePath(\"{value}\"), for:.normal)")
            
            # UIButton的属性
            elif prop == "title":
                code_lines.append(f"{var_name}.setTitle(\"{value}\".localized(), for: .normal)")
            elif prop == "seletedTitle":
                code_lines.append(f"{var_name}.setTitle(\"{value}\".localized(), for:.selected)")
            elif prop == "titleColor":
                code_lines.append(f"{var_name}.setTitleColor({self.swift_color_from_value(value)}, for: .normal)")
            elif prop == "selectedTitleColor":
                code_lines.append(f"{var_name}.setTitleColor({self.swift_color_from_value(value)}, for:.selected)")
            elif prop == "seletedImage":
                code_lines.append(f"{var_name}.setImage(.caTimagePath(\"{value}\"), for:.selected)")
            elif prop == "action":
                if var_type == "UIButton":
                    code_lines.append(f"{var_name}.addTarget(self, action:#selector({value}(sender:)), for:.touchUpInside)")
                elif var_type == "UITextField":
                    code_lines.append(f"{var_name}.addTarget(self, action:#selector({value}(sender:)), for:.editingChanged)")
                elif var_type == "UISlider" or var_type == "UISwitch":
                    code_lines.append(f"{var_name}.addTarget(self, action:#selector({value}(sender:)), for:.valueChanged)")
                
                # 添加点击事件方法
                action_codes = []
                if var_des:
                    action_codes.append(f"// {var_des}的点击事件\n")
                action_codes.append(f"@objc func {value}(sender: {var_type}) {{\n")
                action_codes.append("    // 处理点击事件\n")
                action_codes.append("}\n")
                self.actions.append("".join(action_codes))

            elif prop == "contentHorizontalAlignment":
                code_lines.append(f"{var_name}.contentHorizontalAlignment = .{value}")
            elif prop == "contentVerticalAlignment":
                code_lines.append(f"{var_name}.contentVerticalAlignment = .{value}")
            
            # UITextFeield的属性
            elif prop == "placeholder":
                code_lines.append(f"{var_name}.attributedPlaceholder = .setAttributedPlaceholder(text: \"{value}\".localized())")
            elif prop == "textAlignment":
                code_lines.append(f"{var_name}.textAlignment =.{value}")
            elif prop == "keyboardType":
                code_lines.append(f"{var_name}.keyboardType =.{value}")
            elif prop == "returnKeyType":
                code_lines.append(f"{var_name}.returnKeyType =.{value}")        
            elif prop == "delegate":
                code_lines.append(f"{var_name}.delegate = self")
            
            # UISlider的属性
            elif prop == "minimumValue":
                code_lines.append(f"{var_name}.minimumValue = {value}")
            elif prop == "maximumValue":
                code_lines.append(f"{var_name}.maximumValue = {value}")
            elif prop == "value":
                code_lines.append(f"{var_name}.value = {value}")
            elif prop == "minimumTrackTintColor":
                code_lines.append(f"{var_name}.minimumTrackTintColor = {self.swift_color_from_value(value)}")
            elif prop == "maximumTrackTintColor":
                code_lines.append(f"{var_name}.maximumTrackTintColor = {self.swift_color_from_value(value)}")
            elif prop == "thumbTintColor":
                code_lines.append(f"{var_name}.thumbTintColor = {self.swift_color_from_value(value)}")
            
            # UISwitch的属性
            elif prop == "onTintColor":
                code_lines.append(f"{var_name}.onTintColor = {self.swift_color_from_value(value)}")
            elif prop == "isOn":
                code_lines.append(f"{var_name}.isOn = {str(value).lower()}")
            elif prop == "transform":
                code_lines.append(f"{var_name}.transform = CGAffineTransform(scaleX: {value}, y: {value})")
            elif prop == "thumbTintColor":
                code_lines.append(f"{var_name}.thumbTintColor = {self.swift_color_from_value(value)}")
            

        if is_return:
            code_lines.append(f"return {var_name}")      
            
        
        # 使用列表推导式添加缩进并连接所有行
        return "\n".join(code_lines)
    
    def set_constraints(self, var_name, constraints, parent_name=None):
        """设置约束"""
        codes = []
        for key, value in constraints.items():
            # if "parent" in value:
            #     value = value.replace("parent", parent_name)
            
            if key == "width":
                codes.append(f"make.width.equalTo({value})\n")
            elif key == "height":
                codes.append(f"make.height.equalTo({value})\n")
            elif key == "leading":
                codes.append(f"make.leading.equalTo({value})\n")
            elif key == "trailing":
                codes.append(f"make.trailing.equalTo(-{value})\n")
            elif key == "top":
                codes.append(f"make.top.equalTo({value})\n")
            elif key == "bottom":
                codes.append(f"make.bottom.equalTo(-{value})\n")
            elif key == "centerX":
                codes.append(f"make.centerX.equalTo({value})\n")
            elif key == "centerY":
                codes.append(f"make.centerY.equalTo({value})\n")
        
        # 修改这里：返回codes而不是code
        return "".join(codes)
    
    def create_view(self, view_data, parent_name="view", var_prefix="", father_view=None):
        """创建视图"""

        if not father_view:
            father_view = 'self'

        view_type = view_data.get("view_type", "")
        if not view_type:
            view_type = view_data.get("viewType", "UIView")
        # 从26个小写字母随机获取一个
        a = random.choice(string.ascii_lowercase)
        var_name = self.gen_words.generate_words(1, uikit_type=view_type, prefix=a)
        codes = []
        constraint_code = []
        if view_des := view_data.get("view_des"):
            codes.append(f"// {view_des}\n")
            constraint_code.append(f"/// {view_des}\n")  # 添加换行符
        codes.append(f"public lazy var {var_name}: {view_type} = {{\n")



        # 设置属性
        if "properties" in view_data:
            temp_name, code = self.generate_uikit_let_code(view_type)
            codes.append(code)
            codes.append(self.set_uikit_properties(temp_name, view_data["properties"], view_type, is_return=True))
        
        # 设置约束
        
        if "constraints" in view_data:
            constraint_code.append(f"{father_view}.addSubview({var_name})\n")  # 添加换行符
            constraint_code.append(f"{var_name}.snp.makeConstraints {{ make in\n")
            temp_code = self.set_constraints(var_name, view_data["constraints"], parent_name)
            constraint_code.append(temp_code)
            constraint_code.append("}\n")  # 添加换行符
            

        codes.append("}()\n")
        constraint_code.append("\n")  # 添加换行符
        
        return "".join(codes), "".join(constraint_code)
    

    def generate_uikit_let_code(self, var_type):
        """声明UIKit代码"""
        var_name = GenerateWordsUtil().generate_words(1)
        code = ""
        if var_type == "UIButton":
            code = f"let {var_name}: UIButton = UIButton(type: .custom)\n"
        else:
            code = f"let {var_name}: {var_type} = {var_type}()\n"

        return var_name, code
    
    def get_uikit_codes(self, json_data):
        """根据JSON数据生成UIKit代码"""
        if isinstance(json_data, str):
            try:
                json_data = json.loads(json_data)
            except json.JSONDecodeError:
                # 尝试修复不完整的JSON
                json_data = json.loads('{"' + json_data)
        
        code = ""
        
        # 处理根视图
        if "view_type" in json_data:
            code += self.create_view(json_data)
        # 处理子视图列表
        elif "subviews" in json_data:
            for i, subview in enumerate(json_data["subviews"]):
                sub_prefix = f"sub{i}_"
                code += self.create_view(subview, var_prefix=sub_prefix)
        
        return code
    
    # 添加该类方法
    def generate_class_method(self, class_name, is_class_return=True):
        """生成类方法"""
        codes = []
        
        # 处理类名前缀
        # 只保留类名前面的一个大写字母
        processed_name = class_name
        if len(class_name) > 1:
            # 保留第一个字符，从第二个字符开始查找大写字母
            first_char = ''
            
            for i in range(len(class_name)):
                if class_name[i].isupper():
                    # 只保留第一个大写字母和后面的部分
                    first_char = class_name[i]
                else:
                    # 保留第一个字符和后面的部分
                    processed_name = first_char + class_name[i:]
                    break
        
        codes.append(f"\tpublic class func vhpop{processed_name}(vhdyV: UIView?) -> {class_name}! {{\n")
        codes.append(f"\t\t{class_name}.vhbsRemove(String(describing: {class_name}.self))\n")
        codes.append(f"\t\tlet vhbsview = {class_name}(frame: CGRect(x: 0, y: 0, width: VHbsWidth, height: VHbsHeigth))\n")
        codes.append(f"\t\tif vhdyV != nil {{\n")
        codes.append(f"\t\t\tvhdyV!.addSubview(vhbsview)\n")
        codes.append(f"\t\t}}\n")
        codes.append(f"\t\telse{{\n")
        codes.append(f"\t\t\tvhbsWindow()?.addSubview(vhbsview)\n")
        codes.append(f"\t\t}}\n")
        codes.append(f"\t\treturn vhbsview")
        codes.append("\t}\n")  # 确保这里有闭合括号
        return "".join(codes)
    

    def swift_color_from_value(self, rgb_value):
        """
        将rgba(r, g, b, a)格式的颜色转换为Swift中的UIColor初始化格式
        例如：rgba(0, 0, 0, 1) => UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0)
        """
        # 检查是否为rgba格式
        if not isinstance(rgb_value, str) or not rgb_value.startswith("rgba("):
            return f".{rgb_value}" if rgb_value else ".clear"
        
        # 移除rgba()部分，只保留括号内的值
        rgba_values = rgb_value.replace("rgba(", "").replace(")", "").split(",")
        
        # 确保有4个值
        if len(rgba_values) != 4:
            return ".black"  # 默认返回黑色
        
        try:
            # 解析RGBA值
            r = float(rgba_values[0].strip())
            g = float(rgba_values[1].strip())
            b = float(rgba_values[2].strip())
            a = float(rgba_values[3].strip())
            
            # 返回Swift格式的UIColor初始化
            if r==g==b==0:
                return ".black"
            elif r==g==b==255:
                return ".white"

            return f"UIColor(red: {r}/255.0, green: {g}/255.0, blue: {b}/255.0, alpha: {a})"
        except ValueError:
            # 如果解析失败，返回默认颜色
            return ".black"
        
